const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('开始获取活动类型列表...')
  
  try {
    const activitiesCollection = db.collection('activities')
    
    // 获取所有活动的type字段，去重
    const result = await activitiesCollection
      .field({
        type: true
      })
      .get()
    
    console.log('获取到的活动数据:', result.data.length, '条')
    
    if (result.data && result.data.length > 0) {
      // 提取所有type值并去重
      const types = [...new Set(result.data
        .map(activity => activity.type)
        .filter(type => type && type.trim() !== '')
      )]
      
      console.log('提取到的活动类型:', types)
      
      // 构建分类列表，'全部'固定在第一位
      const categoryList = [
        { id: 'all', name: '全部' },
        ...types.map(type => ({
          id: type,
          name: type
        }))
      ]
      
      return {
        success: true,
        data: categoryList,
        message: `成功获取 ${types.length} 个活动类型`
      }
    } else {
      // 如果没有活动数据，返回默认的分类列表
      const defaultCategories = [
        { id: 'all', name: '全部' }
      ]
      
      return {
        success: true,
        data: defaultCategories,
        message: '暂无活动数据，返回默认分类'
      }
    }
    
  } catch (error) {
    console.error('获取活动类型失败:', error)
    return {
      success: false,
      error: error.message,
      message: '获取活动类型失败'
    }
  }
}